import { globalEventEmitter, GLOBAL_EVENTS } from './eventEmitter';
import { useState, useEffect } from 'react';

// 使用全局事件常量
export const PAYMENT_EVENTS = GLOBAL_EVENTS;

class PaymentTimer {
  constructor() {
    this.currentTime = 45;
    this.isRunning = false;
    this.timer = null;
    this.emitter = globalEventEmitter;
    this.isInitialized = false;
  }

  // 开始倒计时
  start(initialTime = 45) {
    // 防止重复初始化
    if (this.isInitialized && this.isRunning) {
      console.log('Timer already running, skipping start');
      return;
    }
    
    this.stop(); // 先停止之前的计时器
    
    this.currentTime = initialTime;
    this.isRunning = true;
    this.isInitialized = true;
    
    console.log('Starting timer with time:', this.currentTime);
    
    this.emitter.emit(PAYMENT_EVENTS.PAYMENT_COUNTDOWN_UPDATE, {
      time: this.currentTime,
      isRunning: this.isRunning
    });

    this.timer = setInterval(() => {
      this.currentTime -= 1;
      
      this.emitter.emit(PAYMENT_EVENTS.PAYMENT_COUNTDOWN_UPDATE, {
        time: this.currentTime,
        isRunning: this.isRunning
      });

      if (this.currentTime <= 0) {
        this.handleFinish();
      }
    }, 1000);
  }

  // 停止倒计时
  stop() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
      console.log('Timer stopped');
    }
    this.isRunning = false;
  }

  // 重置倒计时
  reset(newTime = 45) {
    console.log('Resetting timer to:', newTime);
    this.stop();
    this.currentTime = newTime;
    
    this.emitter.emit(PAYMENT_EVENTS.PAYMENT_COUNTDOWN_RESET, {
      time: this.currentTime
    });
    
    this.start(newTime);
  }

  // 倒计时结束处理
  handleFinish() {
    this.stop();
    
    this.emitter.emit(PAYMENT_EVENTS.PAYMENT_COUNTDOWN_FINISH, {
      time: 0
    });

    // 自动重置并重新开始
    this.reset(45);
    
    // 触发支付码刷新事件
    this.emitter.emit(PAYMENT_EVENTS.PAYMENT_CODE_REFRESH, {
      reason: 'timeout',
      timestamp: Date.now()
    });
  }

  // 手动刷新支付码
  refreshPaymentCode() {
    this.reset(45);
    
    this.emitter.emit(PAYMENT_EVENTS.PAYMENT_CODE_REFRESH, {
      reason: 'manual',
      timestamp: Date.now()
    });
  }

  // 获取当前状态
  getStatus() {
    return {
      time: this.currentTime,
      isRunning: this.isRunning
    };
  }

  // 销毁定时器
  destroy() {
    this.stop();
    this.isInitialized = false;
  }
}

// 创建全局实例
export const globalPaymentTimer = new PaymentTimer();

// 便捷的Hook
export const useGlobalPaymentTimer = () => {
  const [timerState, setTimerState] = useState(() => 
    globalPaymentTimer.getStatus()
  );

  useEffect(() => {
    // 监听倒计时更新
    const handleUpdate = (data) => {
      console.log('Timer update received:', data);
      setTimerState(data);
    };
    
    const handleReset = (data) => {
      console.log('Timer reset received:', data);
      setTimerState(data);
    };

    globalPaymentTimer.emitter.on(PAYMENT_EVENTS.PAYMENT_COUNTDOWN_UPDATE, handleUpdate);
    globalPaymentTimer.emitter.on(PAYMENT_EVENTS.PAYMENT_COUNTDOWN_RESET, handleReset);

    // 组件卸载时清理监听器
    return () => {
      globalPaymentTimer.emitter.off(PAYMENT_EVENTS.PAYMENT_COUNTDOWN_UPDATE, handleUpdate);
      globalPaymentTimer.emitter.off(PAYMENT_EVENTS.PAYMENT_COUNTDOWN_RESET, handleReset);
    };
  }, []);

  return {
    ...timerState,
    refresh: () => globalPaymentTimer.refreshPaymentCode(),
    reset: (time) => globalPaymentTimer.reset(time),
    start: (time) => globalPaymentTimer.start(time),
    stop: () => globalPaymentTimer.stop()
  };
};

export default PaymentTimer;